package com.lingjtx.im.core.handle;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.DecoderException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@ChannelHandler.Sharable
@Component
public class ExceptionHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 1. 打印异常日志（区分异常类型）
        if (cause instanceof DecoderException) {
            log.warn("协议解码失败: {}", cause.getMessage());
        } else if (cause instanceof IOException) {
            log.warn("IO异常: {}", cause.getMessage());
        } else {
            log.error("未知异常", cause);
        }

        // 2. 关闭连接（重要！）
        ctx.close();
    }
}
